var window_and_tab_info;
var discovery;

function setLinks(Discovery){
	setLinksHTML(Discovery);
	discovery = Discovery;
}

function initLoad(){
	var bg = chrome.extension.getBackgroundPage();
	if(bg.isItFirstTime()) loadForFirstTime();
	else refreshAddOn();
}

function setWindowAndTabInfo(wati) {
	window_and_tab_info = wati;
}
function refreshAddOn() {
	var bg = chrome.extension.getBackgroundPage();
	bg.getWindowAndTabInfo();
	bg.catchContent();
	bg.receiveKeywords();
	bg.receiveReferences();
}

function loadForFirstTime() {
	var bg = chrome.extension.getBackgroundPage();
	bg.reset();
	bg.getWindowAndTabInfo();
	bg.defineHome();
	bg.catchContent();
}
function addNK(priority, keyword) {
	var bg = chrome.extension.getBackgroundPage();
	var check = bg.isItOk(priority, keyword);
	if (check.value) {
		bg.addNewKeyword(priority, keyword);
		bg.sortKeywords();
		bg.receiveReferences();
	} else
		throw check.errorMessage;
}

function deleteKeyword(priority) {
	var bg = chrome.extension.getBackgroundPage();
	bg.deleteKeyword(priority);
	bg.sortKeywords();
	bg.receiveReferences();
}

function cancelEditingKeyword() {
	var bg = chrome.extension.getBackgroundPage();
	bg.sendCommandToHippo("keywords");
}

function saveEK(row_index, priority, keyword) {
	var bg = chrome.extension.getBackgroundPage();
	var oldKeyword = bg.getKeywordByPriority(row_index);
	var check = bg.isItOk(priority, keyword, oldKeyword);
	if (check.value) {
		bg.editKeyword(priority, keyword, oldKeyword);
		bg.sortKeywords();
		bg.receiveReferences();
	} else
		throw check.errorMessage;
}

function changePriority(priority, new_priority){
	var bg = chrome.extension.getBackgroundPage();
	var keyword = bg.getKeywordByPriority(priority);
	var np = new_priority;
	var check = bg.isItOk(np, keyword, keyword);
	if (check.value) {
		bg.editKeyword(np, keyword, keyword);
		bg.sortKeywords();
		bg.receiveReferences();
	} else
		throw check.errorMessage;
}

function createTabData() {
	return {
		'index' : window_and_tab_info.tab_index + 1,
		'windowId' : window_and_tab_info.window_id,
		'url' : "new_tab.html", //khm, khm!
		'selected' : true
	};
}

function openLink(id_group) {
	var args = createTabData();
	try {
		chrome.tabs.create(args);
		chrome.tabs.update(window_and_tab_info.tab_id, {
			selected : false
		});
	} catch (e) {
		alert(e);
	}
//	setInterval("setGL("+id_group+")", 10);
	setGL(id_group);
}
function setGL(id_group){
	var bg = chrome.extension.getBackgroundPage();
	bg.setGroupLinks(id_group);
}
function copySelectedText() {
	var bg = chrome.extension.getBackgroundPage();
	bg.copyToHome();
}
function changeHomeToCurrentPage(){
	loadForFirstTime();
}
